<?php
	class FacebookUser extends AppModel
	{
		var $name = "FacebookUser";
		
		function isUserRegistered($fbId)
		{
			return $this->hasAny(array('facebook_id'=>$fbId));
		}
		
		function registerByFbId($fbId)
		{
			$userData = array();
			$fbInfo = FacebookApi::getInstance()->api('/me');
			$fbData = $this->getFbRegisterData($fbId,$fbInfo);
			$this->saveUser($fbData,$fbId,$fbInfo,array("validate"=>false));
			return true;
		}
		
		private function saveUser($data,$fbId,$fbInfo,$options = array())
		{
			$UserModel = cri("Sociable.FacebookConfig")->getUserModel();
			$userData = array($UserModel->alias => $data);
			$UserModel->create();
			$return = $UserModel->save($userData,$options);
			$userId = false;
			if($return)
			{
				$userId = $UserModel->id;
				$this->create();
				$data[$this->alias] = array("user_id"=>$userId,"facebook_id"=>$fbId,'regiserted_as_user'=>1); 
				$this->save($data);
				callHooks('OnFacebookUserRegister','.+',$this,$userId,$fbInfo);
			}
			return $userId;
		}
		/**
		 * reutns a password for the fb user that will be stored in db
		 * @param unknown_type $fbId
		 */
		function getPassword($fbId,$hash=true)
		{
			$secretString = cr("Facebook.passwordSecretString");
			if(!$secretString)
			{
				$secretString = "fb_user_pass_";
			}
			$password = $secretString.$fbId;
			if($hash)
			{
				$password = Security::hash($password,null,true);
			}
			return $password;
				
		}
		
		function getFacebookUserId($fbId)
		{
			return $this->field("user_id",array("facebook_id"=>$fbId));
		}
		
		function getFbRegisterData($fbId,$fbInfo = null)
		{
			if(is_null($fbInfo))
			{
				$fbInfo = FacebookApi::getInstance()->api('/me');
			}
			$this->fbData = array('last_name'=>$fbInfo["last_name"],'first_name'=>$fbInfo["first_name"]);
			$mapFields = cr("FacebookConfig.facebook_fields");
			if(is_array($mapFields))
			{
				foreach($mapFields as $userField => $fbField)
				{
					$val = $this->getFbfieldInfo($fbField,$fbInfo);
					if(!is_null($val))
					{
						$this->fbData[$userField] = $val;
					}
				}
			}
			
			$this->fbData = am($this->fbData,array('email'=>$fbInfo['email'],'password'=>$this->getPassword($fbId),
								//necessary for valdiation
			'emailVerified'=>1,'confirm_password'=>$this->getPassword($fbId,false)));
			//this hook is to used to modify data that will be used to save in User model table.
			callHooks("SetFacebookUserRegisterData",'.+',$this,$fbInfo);
			$fbData = $this->fbData;
			return $fbData;
		}
		/**
		 * reurns a valid value of fb field
		 * @param unknown_type $fbField
		 * @param unknown_type $fbInfo
		 */
		function getFbfieldInfo($fbField,$fbInfo)
		{
			$value = null;
			if(isset($fbInfo[$fbField]))
			{
				$value = $fbInfo[$fbField];
			}
			if(!is_string($value))
			{
				switch ($fbField)
				{
					case 'hometown':
                        $value = null;
                        if(isset($fbInfo[$fbField]))
						{
                          $value = $fbInfo[$fbField]['name'];
                        }
                      break;
					case 'picture':
						$value = FacebookApi::getInstance()->apiProfilePhotoUrl("me");
						$image = file_get_contents($value);
						$uploadPath = $this->getUploadImagePath($fbInfo['id']);
						if(!is_dir(dirname($uploadPath)))
						{
							mkdir(dirname($uploadPath),0777);
						}
						if(file_exists($uploadPath))
						{
							unlink($uploadPath);
						}
						file_put_contents($uploadPath,$image);
						$value = basename($uploadPath);
						break;
				}
			}
			return $value;
		}
		
		function registerUser($fbId,$fieldData)
		{
			$UserModel = cri("Sociable.FacebookConfig")->getUserModel();
			$registerFieldGroup = cr("Facebook.registerGroup");
			$registerFields = $UserModel->getFields('group',$registerFieldGroup);
			$fieldsPresent = array_intersect_key(array_combine($registerFields,$registerFields),$fieldData);
			if(count($fieldsPresent) < count($registerFields))
			{
				return false;
			}
			$upload = false;
			$mapFields = cr("FacebookConfig.facebook_fields");
			if(!$mapFields)
			{
				$mapFields = array();
			}
			if(in_array("picture",$mapFields))
			{
				$upload = true;
				$UserModel->Behaviors->detach("Upload");
			}
			$userData = array();
			$fbInfo = FacebookApi::getInstance()->api('/me');
			$fbData = $this->getFbRegisterData($fbId,$fbInfo);
			$fieldData = am($fbData,$fieldData);
			$userId = $this->saveUser($fieldData,$fbId,$fbInfo);
			if($userId == false && $upload)
			{
				unlink($this->getUploadImagePath($fbId));
			}
			return $userId;
			
		}
		
		private function getUploadImagePath($fbId)
		{
			$filePath = cr("Facebook.userUploadDir");
			if(!$filePath)
			{
				$filePath = WWW_ROOT."uploads".DS."avatar";
			}
			$ext = substr($fbId,0,6).time();
			$filename = "fb_photo_name_".$ext.'.jpg';
			return $filePath.DS.$filename;
		}
		
		function isFacebookUser($userId)
		{
			return $this->hasAny(array("user_id"=>$userId));
		}
	}
?>